import axios from "axios";
import getUserTempId from "./getUserTempId";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false });
const request = axios.create({
	baseURL: "/api",
	timeout: 5000,
	headers: {},
});
request.interceptors.request.use((config) => {
	NProgress.start();
	const token = JSON.parse(localStorage.getItem("token"));
	if (token) {
		config.headers.token = token;
	}
	config.headers.userTempId = getUserTempId();
	return config;
});
request.interceptors.response.use(
	(response) => {
		NProgress.done();
		if (response.data.code === 200) {
			return response.data.data;
		} else {
			// 功能失败：1. 将promise对象的状态改为失败状态 3. 返回失败的原因 response.data.message
			alert(response.data.message);
			return Promise.reject(response.data.message);
		}
	},
	(error) => {
		NProgress.done();
		alert(error);
		return Promise.reject(error);
	}
);
export default request;
